/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 *@param 实验现象：串口2接收数据然后传递给舵机，角度为0-180
 *@param 舵机引脚：PA6
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-05-06     洪家团    first version
 */

#include <rtthread.h>
#include "servos.h"

#define SAMPLE_UART_NAME       "uart2"
/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
static rt_device_t serial;

static rt_err_t uart_input(rt_device_t dev, rt_size_t size);
void uart_init(void);

unsigned char angel=0; //舵机角度   0-180


int main(void)
{
    servos_init();
    uart_init();

    while(1)
    {
        if(angel>180)
            angel=180;

        //servos_turn(500000+120*(2000000/180));
        servos_turn(500000+angel*(2000000/180));   //舵机转动到0度  500000-2500000
        rt_thread_mdelay(1000);

        //servos_turn(500000+30*(2000000/180));
        //rt_thread_mdelay(1000);
    }

    return RT_EOK;
}


/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    unsigned char ch;
    rt_device_read(serial, -1, &ch, 1);

    angel=ch;
    /* 读取到的数据通过串口输出 */
    rt_device_write(serial, 0, &ch, 1);

    return RT_EOK;
}

void uart_init(void)
{
    /* 查找系统中的串口设备 */
    serial = rt_device_find(SAMPLE_UART_NAME);
    if (!serial)
    {
        rt_kprintf("find %s failed!\n", SAMPLE_UART_NAME);
        return RT_ERROR;
    }

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);
}


